package com.ugoodtech.mdcc.core.repository;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

import com.ugoodtech.mdcc.core.domain.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

public interface UserRepository extends PagingAndSortingRepository<User, Long>
        , QueryDslPredicateExecutor<User> {

    @Query("from User where username=:username and station_id=:stationId")
    User findByUsernameAndStationId(@Param("username") String username, @Param("stationId") Long stationId);

    User findByUsername(String username);

    @Query("from User where openId=:openId and deleted=false and enabled=true")
    User findByOpenId(@Param("openId") String openId);

    @Query(value = "select a.id from users a left join user_profiles b on b.user_id=a.id where b.realName like :username", nativeQuery = true)
    List<Object> finLikeName(@Param("username") String username);

    @Query(value = "SELECT * FROM users WHERE openId=:openId AND username !=:phone AND deleted=false AND enabled=true", nativeQuery = true)
    List<User> finByOpenIdAndNotEqPhone(@Param("openId") String openId, @Param("phone") String phone);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update User b set b.deleted=true where b.id=:id")
    void delete(@Param("id") Long id);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update User b set b.deleted=true where b.id in :ids")
    void delete(@Param("ids") Collection<Long> ids);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update User b set b.enabled=false where b.id in :ids")
    void disable(@Param("ids") Collection<Long> ids);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update User b set b.enabled=true where b.id in :ids")
    void enable(@Param("ids") Collection<Long> ids);

//    List<User> findByTelephoneContaining(String phoneNumber);

//    @Query("from User where enabled=true and  position = :position")
//    List<User> findByPosition(@Param("position") Position position);


    @Query("from User where enabled=true and  manager = :manager")
    List<User> findByManager(@Param("manager") User manager);

    @Query("from User where username=:phone and deleted=false and enabled=true")
    User findByUserName_phone(@Param("phone") String phone);


}
